package com.example.doc.core.utils;

import com.example.doc.model.FileInfo;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;

public class FileUtils {

    /**
     * 获取服务器路径
     * @return
     */
    public static String getServerPath(){
        try {
            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            if (path.exists())
                return path.getAbsolutePath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return new File("").getAbsolutePath();
    }

    public static void createFolderIfNotExist(String filePath){
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    /**
     * 上传文件
     * @param file
     * @param type
     */
    public static FileInfo uploadFile(MultipartFile file, String type){
        String filename = file.getOriginalFilename();
        //定义上级目录名称
        String folderName = createSemiRandomName(filename);
        String path = "/upload/"+ type+"/"+folderName+"/";
        String resourcePath = FileUtils.getServerPath();
        FileUtils.createFolderIfNotExist(resourcePath + path);

        //文件上传相对路径
        String filePath = path + filename;
        FileUtils.transferFile(file,resourcePath + filePath);

        FileInfo fileInfo = new FileInfo();
        fileInfo.setFilename(filename);
        fileInfo.setFilepath(filePath);
        return fileInfo;
    }

    /**
     * 根据文件名生成一个半随机名称（去除所有点号的文件名 + 时间戳 + 随机6位字符串）
     * @param fileName 文件名
     * @return
     */
    public static String createSemiRandomName(String fileName) {
        // 去除所有点号
        String fileNameTemp = fileName.replaceAll("\\.", "");
        // 生成时间戳
        String timestamp = DateUtils.format(new Date(), "yyyyMMddHHmmssSSS");
        // 生成随机6位字符串
        return fileNameTemp + "-" + timestamp;
    }


    public static void transferFile(MultipartFile file ,String path){
        try {
            file.transferTo(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void downloadFile(HttpServletResponse response,String filepath){
        response.setContentType("multipart/form-data");
        String codedFileName = "";
        OutputStream os = null;
        FileInputStream fis = null;
        BufferedInputStream bis = null;

        try {
            File file = new File(filepath);
            if (!file.exists())
                return;
            //以流的形式下载
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            codedFileName = "\"" + new String(file.getName().getBytes("gb2312"), StandardCharsets.ISO_8859_1)+"\"";
//            codedFileName = java.net.URLEncoder.encode(file.getName(), "UTF-8");
            //清空response
            response.reset();
            response.setHeader("content-disposition","attachment;filename="+codedFileName);
            os = new BufferedOutputStream(response.getOutputStream());
            os.write(buffer);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis!=null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 输出指定文件的byte数组
     *
     * @param filePath 文件路径
     * @param os 输出流
     * @return
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException
    {
        FileInputStream fis = null;

        try {
            File file = new File(filePath);
            if (!file.exists()){
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b))>0){
                os.write(b,0,length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null)
            {
                try
                {
                    os.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
            if (fis != null)
            {
                try
                {
                    fis.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 下载文件名重新编码
     *
     * @param request 请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName)
            throws UnsupportedEncodingException
    {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE"))
        {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        }
        else if (agent.contains("Firefox"))
        {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        }
        else if (agent.contains("Chrome"))
        {
            // google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        else
        {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }

}
